#pragma once

#include <pthread.h>
#include <cstdio>

namespace mutexModule
{

    class Mutex
    {
    public:

        Mutex()
        {
            int num = pthread_mutex_init(&_mutex, nullptr);
            if (num != 0)
            {
                perror("pthread_mutex_init");
            }
        }

        void lock()
        {
            int num = pthread_mutex_lock(&_mutex);
            if (num != 0)
            {
                perror("pthread_mutex_lock");
            }
        }

        void unlock()
        {
            int num = pthread_mutex_unlock(&_mutex);
            if (num != 0)
            {
                perror("pthread_mutex_unlock");
            }
        }

        pthread_mutex_t* getMutex()
        {
            return &_mutex;
        }

        ~Mutex()
        {
            int num = pthread_mutex_destroy(&_mutex);
            if (num != 0)
            {
                perror("pthread_mutex_destroy");
            }
        }

    private:

        pthread_mutex_t _mutex;
    };

    class MutexGuard
    {
    public:

        MutexGuard(Mutex& mutex)
            :_mutex(mutex)
        {
            _mutex.lock();
        }

        ~MutexGuard()
        {
            _mutex.unlock();
        }

    private:

        Mutex& _mutex;
    };
}
